// 币种列表
const currencies = [
  { label: '全部币种', value: 'all', icon: '💰', bgColor: '#f0f9ff' },
  { label: 'HDFS', value: 'HDFS', icon: '💎', bgColor: '#e6f7ff' },
  { label: 'USDT', value: 'USDT', icon: '💵', bgColor: '#e8f5e9' },
  { label: 'ETH', value: 'ETH', icon: '⚡', bgColor: '#f0e6ff' },
  { label: 'BTC', value: 'BTC', icon: '🔶', bgColor: '#fff7e6' }
]

// 生成随机记录
const generateRecords = (count = 50) => {
  const records = []
  const types = ['deposit', 'withdraw', 'transfer_in', 'transfer_out', 'interest', 'reward', 'fee']
  const statuses = ['completed', 'pending', 'failed']
  const typeToCategory = {
    'deposit': 'income',
    'withdraw': 'expense',
    'transfer_in': 'income',
    'transfer_out': 'expense',
    'interest': 'income',
    'reward': 'income',
    'fee': 'expense'
  }
  
  for (let i = 0; i < count; i++) {
    const type = types[Math.floor(Math.random() * types.length)]
    const currency = currencies[Math.floor(Math.random() * (currencies.length - 1)) + 1].value
    const status = statuses[Math.floor(Math.random() * statuses.length)]
    const category = typeToCategory[type]
    
    // 生成随机日期（最近30天内）
    const date = new Date()
    date.setDate(date.getDate() - Math.floor(Math.random() * 30))
    const dateStr = date.toISOString().split('T')[0]
    
    // 生成随机时间
    const hours = String(Math.floor(Math.random() * 24)).padStart(2, '0')
    const minutes = String(Math.floor(Math.random() * 60)).padStart(2, '0')
    const seconds = String(Math.floor(Math.random() * 60)).padStart(2, '0')
    const timeStr = `${dateStr} ${hours}:${minutes}:${seconds}`
    
    // 生成随机金额（1-1000之间，保留2位小数）
    const amount = (Math.random() * 999 + 1).toFixed(2)
    
    // 生成随机手续费（金额的0-2%）
    const fee = type === 'withdraw' ? (amount * (Math.random() * 0.02)).toFixed(2) : null
    
    // 生成随机哈希（对于已完成的交易）
    const hash = status === 'completed' ? `0x${Math.random().toString(16).substring(2, 42)}` : null
    
    // 生成随机地址（对于提现交易）
    const address = type === 'withdraw' ? `0x${Math.random().toString(16).substring(2, 42)}` : null
    
    // 生成随机关联用户（对于转账交易）
    const relatedUser = (type === 'transfer_in' || type === 'transfer_out') ? `用户${Math.floor(Math.random() * 900000) + 100000}` : null
    
    records.push({
      id: `rec${String(i + 1).padStart(3, '0')}`,
      type,
      amount,
      currency,
      date: dateStr,
      time: timeStr,
      status,
      hash,
      address,
      fee,
      relatedUser,
      category,
      remark: Math.random() > 0.7 ? '用户备注信息' : null
    })
  }
  
  // 按日期降序排序
  records.sort((a, b) => new Date(b.time) - new Date(a.time))
  
  return records
}

// 所有记录（用于筛选）
const allRecords = generateRecords(50)

/**
 * 获取币种流水记录列表
 * @param {Object} params 查询参数
 * @returns {Object} 响应数据
 */
export function getRecordList(params = {}) {
  const {
    currency = 'all',
    type = 'all',
    status = 'all',
    startDate,
    endDate,
    page = 1,
    pageSize = 10
  } = params
  
  // 筛选记录
  let filteredRecords = [...allRecords]
  
  if (currency && currency !== 'all') {
    filteredRecords = filteredRecords.filter(record => record.currency === currency)
  }
  
  if (type && type !== 'all') {
    filteredRecords = filteredRecords.filter(record => record.category === type)
  }
  
  if (status && status !== 'all') {
    filteredRecords = filteredRecords.filter(record => record.status === status)
  }
  
  if (startDate) {
    filteredRecords = filteredRecords.filter(record => record.date >= startDate)
  }
  
  if (endDate) {
    filteredRecords = filteredRecords.filter(record => record.date <= endDate)
  }
  
  // 分页
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const records = filteredRecords.slice(start, end)
  
  return {
    code: 0,
    message: 'success',
    data: {
      records,
      total: filteredRecords.length,
      page,
      pageSize
    }
  }
}

/**
 * 获取币种流水统计数据
 * @param {Object} params 查询参数
 * @returns {Object} 响应数据
 */
export function getRecordStatistics(params = {}) {
  const {
    currency = 'all',
    period = 'month'
  } = params
  
  // 筛选记录
  let filteredRecords = [...allRecords]
  
  if (currency && currency !== 'all') {
    filteredRecords = filteredRecords.filter(record => record.currency === currency)
  }
  
  // 根据周期筛选
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).toISOString().split('T')[0]
  
  if (period === 'today') {
    filteredRecords = filteredRecords.filter(record => record.date === today)
  } else if (period === 'week') {
    const weekStart = new Date(now)
    weekStart.setDate(now.getDate() - now.getDay())
    weekStart.setHours(0, 0, 0, 0)
    filteredRecords = filteredRecords.filter(record => new Date(record.date) >= weekStart)
  } else if (period === 'month') {
    const monthStart = new Date(now.getFullYear(), now.getMonth(), 1)
    filteredRecords = filteredRecords.filter(record => new Date(record.date) >= monthStart)
  } else if (period === 'lastMonth') {
    const lastMonthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1)
    const lastMonthEnd = new Date(now.getFullYear(), now.getMonth(), 0)
    filteredRecords = filteredRecords.filter(record => {
      const recordDate = new Date(record.date)
      return recordDate >= lastMonthStart && recordDate <= lastMonthEnd
    })
  } else if (period === 'year') {
    const yearStart = new Date(now.getFullYear(), 0, 1)
    filteredRecords = filteredRecords.filter(record => new Date(record.date) >= yearStart)
  }
  
  // 计算收入和支出
  let income = 0
  let expense = 0
  
  filteredRecords.forEach(record => {
    if (record.category === 'income') {
      income += parseFloat(record.amount)
    } else if (record.category === 'expense') {
      expense += parseFloat(record.amount)
    }
  })
  
  // 生成趋势数据（最近7天）
  const trend = []
  for (let i = 6; i >= 0; i--) {
    const date = new Date()
    date.setDate(date.getDate() - i)
    const dateStr = date.toISOString().split('T')[0]
    
    const dayRecords = filteredRecords.filter(record => record.date === dateStr)
    
    let dayIncome = 0
    let dayExpense = 0
    
    dayRecords.forEach(record => {
      if (record.category === 'income') {
        dayIncome += parseFloat(record.amount)
      } else if (record.category === 'expense') {
        dayExpense += parseFloat(record.amount)
      }
    })
    
    trend.push({
      date: dateStr,
      income: dayIncome.toFixed(2),
      expense: dayExpense.toFixed(2)
    })
  }
  
  return {
    code: 0,
    message: 'success',
    data: {
      income: income.toFixed(2),
      expense: expense.toFixed(2),
      trend
    }
  }
}

/**
 * 获取币种流水详情
 * @param {string} id 流水记录ID
 * @returns {Object} 响应数据
 */
export function getRecordDetail(id) {
  const record = allRecords.find(item => item.id === id) || allRecords[0]
  
  return {
    code: 0,
    message: 'success',
    data: record
  }
}

/**
 * 获取交易详情
 * @param {string} id 交易ID
 * @returns {Object} 响应数据
 */
export function getTransactionDetail(id) {
  // 这里使用流水记录作为交易详情的模拟数据
  // 实际项目中可能需要更详细的交易数据结构
  const transaction = allRecords.find(item => item.id === id) || allRecords[0]
  
  // 添加一些交易特有的字段
  const transactionDetail = {
    ...transaction,
    txId: `TX${transaction.id.substring(3)}`,
    confirmations: transaction.status === 'completed' ? Math.floor(Math.random() * 100) + 1 : 0,
    network: transaction.currency === 'ETH' ? 'Ethereum' : 
             transaction.currency === 'BTC' ? 'Bitcoin' : 
             transaction.currency === 'USDT' ? 'Tether' : 'HDFS Chain',
    blockHeight: transaction.status === 'completed' ? Math.floor(Math.random() * 1000000) + 15000000 : null,
    gasUsed: transaction.type === 'withdraw' || transaction.type === 'transfer_out' ? 
             (Math.random() * 0.01).toFixed(6) : null,
    gasPrice: transaction.type === 'withdraw' || transaction.type === 'transfer_out' ? 
              (Math.random() * 100).toFixed(2) + ' Gwei' : null
  }
  
  return {
    code: 0,
    message: 'success',
    data: transactionDetail
  }
}

/**
 * 获取交易记录列表
 * @param {Object} params 查询参数
 * @returns {Object} 响应数据
 */
export function getTransactions(params = {}) {
  const {
    currency,
    type,
    status,
    startDate,
    endDate,
    page = 1,
    pageSize = 10
  } = params
  
  // 筛选记录
  let filteredRecords = [...allRecords]
  
  // 转换记录类型，将transfer_in和transfer_out统一为transfer
  filteredRecords = filteredRecords.map(record => {
    const newRecord = { ...record }
    if (record.type === 'transfer_in' || record.type === 'transfer_out') {
      newRecord.type = 'transfer'
    }
    return newRecord
  })
  
  if (currency) {
    filteredRecords = filteredRecords.filter(record => record.currency === currency)
  }
  
  if (type) {
    filteredRecords = filteredRecords.filter(record => record.type === type)
  }
  
  if (status) {
    filteredRecords = filteredRecords.filter(record => record.status === status)
  }
  
  if (startDate) {
    filteredRecords = filteredRecords.filter(record => record.date >= startDate)
  }
  
  if (endDate) {
    filteredRecords = filteredRecords.filter(record => record.date <= endDate)
  }
  
  // 分页
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const list = filteredRecords.slice(start, end)
  
  return {
    code: 0,
    message: 'success',
    success: true,
    data: {
      list,
      total: filteredRecords.length,
      page,
      pageSize
    }
  }
}

// 支持的充值币种及网络
const supportedCurrencies = [
  {
    currency: 'HDFS',
    name: 'HDFS',
    icon: '💎',
    networks: [
      {
        network: 'HDFS',
        name: 'HDFS链',
        minAmount: '1.00',
        fee: '0',
        confirmations: 12,
        isActive: true
      }
    ]
  },
  {
    currency: 'USDT',
    name: 'USDT',
    icon: '💵',
    networks: [
      {
        network: 'ERC20',
        name: 'ERC20',
        minAmount: '10.00',
        fee: '5.00',
        confirmations: 12,
        isActive: true
      },
      {
        network: 'TRC20',
        name: 'TRC20',
        minAmount: '1.00',
        fee: '1.00',
        confirmations: 6,
        isActive: true
      }
    ]
  },
  {
    currency: 'ETH',
    name: '以太坊',
    icon: '⚡',
    networks: [
      {
        network: 'ETH',
        name: '以太坊主网',
        minAmount: '0.01',
        fee: '0.001',
        confirmations: 12,
        isActive: true
      }
    ]
  },
  {
    currency: 'BTC',
    name: '比特币',
    icon: '🔶',
    networks: [
      {
        network: 'BTC',
        name: '比特币主网',
        minAmount: '0.001',
        fee: '0.0001',
        confirmations: 3,
        isActive: true
      }
    ]
  }
]

// 充值地址
const depositAddresses = {
  'HDFS': {
    'HDFS': {
      address: 'hdfs1q6z3qhnvdzx8z7xq4xm7k6zj89jy8xf7g2l8vr',
      tag: null,
      qrcode: 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=hdfs1q6z3qhnvdzx8z7xq4xm7k6zj89jy8xf7g2l8vr'
    }
  },
  'USDT': {
    'ERC20': {
      address: '0x8f5b2b7d2d376c1b5d8390a6f603aeee1d0e4021',
      tag: null,
      qrcode: 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=0x8f5b2b7d2d376c1b5d8390a6f603aeee1d0e4021'
    },
    'TRC20': {
      address: 'TJYeasTPa6gpEEiNGdQz9jEjsH6GgPz9U9',
      tag: null,
      qrcode: 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=TJYeasTPa6gpEEiNGdQz9jEjsH6GgPz9U9'
    }
  },
  'ETH': {
    'ETH': {
      address: '0x71c7656ec7ab88b098defb751b7401b5f6d8976f',
      tag: null,
      qrcode: 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=0x71c7656ec7ab88b098defb751b7401b5f6d8976f'
    }
  },
  'BTC': {
    'BTC': {
      address: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh',
      tag: null,
      qrcode: 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh'
    }
  }
}

/**
 * 获取支持的充值币种列表
 * @returns {Object} 响应数据
 */
export function getSupportedCurrencies() {
  return {
    code: 0,
    message: 'success',
    success: true,
    data: supportedCurrencies
  }
}

/**
 * 获取充值地址
 * @param {Object|string} params 查询参数或币种字符串
 * @returns {Object} 响应数据
 */
export function getDepositAddress(params) {
  let currency, network;
  
  if (typeof params === 'string') {
    currency = params;
    network = null;
  } else {
    currency = params.currency;
    network = params.network;
  }
  
  // 查找币种
  const currencyInfo = supportedCurrencies.find(c => c.currency === currency);
  if (!currencyInfo) {
    return {
      code: 1,
      message: '不支持的币种',
      success: false,
      data: null
    };
  }
  
  // 如果指定了网络，查找对应网络的地址
  if (network) {
    const networkInfo = currencyInfo.networks.find(n => n.network === network);
    if (!networkInfo || !networkInfo.isActive) {
      return {
        code: 1,
        message: '不支持的网络或网络暂时不可用',
        success: false,
        data: null
      };
    }
  }
  
  // 获取地址
  const addressInfo = depositAddresses[currency];
  if (!addressInfo) {
    return {
      code: 1,
      message: '获取充值地址失败',
      success: false,
      data: null
    };
  }
  
  // 如果指定了网络，返回对应网络的地址
  if (network && addressInfo[network]) {
    return {
      code: 0,
      message: 'success',
      success: true,
      data: addressInfo[network]
    };
  }
  
  // 否则返回默认网络的地址
  const defaultNetwork = currencyInfo.networks[0].network;
  return {
    code: 0,
    message: 'success',
    success: true,
    data: addressInfo[defaultNetwork] || Object.values(addressInfo)[0]
  };
}

/**
 * 获取充值记录
 * @param {Object} params 查询参数
 * @returns {Object} 响应数据
 */
export function getDepositRecords(params = {}) {
  const {
    currency,
    status,
    page = 1,
    pageSize = 10
  } = params;
  
  // 筛选出充值记录
  let filteredRecords = allRecords.filter(record => record.type === 'deposit');
  
  if (currency && currency !== 'all') {
    filteredRecords = filteredRecords.filter(record => record.currency === currency);
  }
  
  if (status && status !== 'all') {
    filteredRecords = filteredRecords.filter(record => record.status === status);
  }
  
  // 分页
  const start = (page - 1) * pageSize;
  const end = start + pageSize;
  const list = filteredRecords.slice(start, end);
  
  return {
    code: 0,
    message: 'success',
    success: true,
    data: {
      list,
      total: filteredRecords.length,
      page,
      pageSize
    }
  };
}

/**
 * 获取可用币种列表
 * @returns {Object} 响应数据
 */
export function getCurrencyList() {
  return {
    code: 0,
    message: 'success',
    data: currencies
  }
}

// 保存的提现地址
const savedWithdrawAddresses = {
  'HDFS': [
    {
      id: '1',
      name: '我的HDFS钱包',
      address: 'hdfs1q6z3qhnvdzx8z7xq4xm7k6zj89jy8xf7g2l8vr',
      isDefault: true
    },
    {
      id: '2',
      name: 'HDFS交易所',
      address: 'hdfs1qwerty123456789abcdefghijklmnopqrstuvwxyz',
      isDefault: false
    }
  ],
  'USDT': [
    {
      id: '3',
      name: '我的USDT钱包',
      address: '0x8f5b2b7d2d376c1b5d8390a6f603aeee1d0e4021',
      isDefault: true
    },
    {
      id: '4',
      name: 'USDT交易所',
      address: '0x71c7656ec7ab88b098defb751b7401b5f6d8976f',
      isDefault: false
    }
  ],
  'ETH': [
    {
      id: '5',
      name: '我的ETH钱包',
      address: '0x71c7656ec7ab88b098defb751b7401b5f6d8976f',
      isDefault: true
    }
  ],
  'BTC': [
    {
      id: '6',
      name: '我的BTC钱包',
      address: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh',
      isDefault: true
    }
  ]
}

/**
 * 获取提现记录
 * @param {Object} params 查询参数
 * @returns {Object} 响应数据
 */
export function getWithdrawRecords(params = {}) {
  const {
    currency,
    status,
    page = 1,
    pageSize = 10
  } = params;
  
  // 筛选出提现记录
  let filteredRecords = allRecords.filter(record => record.type === 'withdraw');
  
  if (currency && currency !== 'all') {
    filteredRecords = filteredRecords.filter(record => record.currency === currency);
  }
  
  if (status && status !== 'all') {
    filteredRecords = filteredRecords.filter(record => record.status === status);
  }
  
  // 分页
  const start = (page - 1) * pageSize;
  const end = start + pageSize;
  const list = filteredRecords.slice(start, end);
  
  return {
    code: 0,
    message: 'success',
    success: true,
    data: {
      list,
      total: filteredRecords.length,
      page,
      pageSize
    }
  };
}

/**
 * 获取保存的提现地址
 * @param {string} currency 币种
 * @returns {Object} 响应数据
 */
export function getSavedAddresses(currency) {
  const addresses = savedWithdrawAddresses[currency] || [];
  
  return {
    code: 0,
    message: 'success',
    success: true,
    data: addresses
  };
}

/**
 * 提交提现申请
 * @param {Object} data 提现数据
 * @returns {Object} 响应数据
 */
export function submitWithdraw(data) {
  const { currency, amount, address } = data;
  
  // 检查必填字段
  if (!currency || !amount || !address) {
    return {
      code: 1,
      message: '请填写完整的提现信息',
      success: false
    };
  }
  
  // 检查金额是否合法
  const amountNum = parseFloat(amount);
  if (isNaN(amountNum) || amountNum <= 0) {
    return {
      code: 1,
      message: '请输入有效的提现金额',
      success: false
    };
  }
  
  // 检查最小提现金额
  if (amountNum < 10) {
    return {
      code: 1,
      message: '提现金额不能小于10',
      success: false
    };
  }
  
  // 生成新的提现记录
  const newWithdraw = {
    id: `rec${Date.now().toString().substring(6)}`,
    type: 'withdraw',
    amount: amountNum.toFixed(2),
    currency,
    date: new Date().toISOString().split('T')[0],
    time: new Date().toISOString().replace('T', ' ').substring(0, 19),
    status: 'pending',
    hash: null,
    address,
    fee: (amountNum * 0.01).toFixed(2),
    category: 'expense',
    remark: null
  };
  
  // 将新记录添加到记录列表中
  allRecords.unshift(newWithdraw);
  
  return {
    code: 0,
    message: '提现申请已提交',
    success: true,
    data: newWithdraw
  };
}
